﻿using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Abp.AspNetCore.Configuration;
using Abp.AspNetCore.Mvc.Auditing;
using Abp.AspNetCore.Mvc.ExceptionHandling;
using Abp.Auditing;
using Abp.Dependency;
using Abp.Runtime.Caching;
using Abp.Web.Models;
using Castle.Core.Logging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Partner.Utility;

namespace HCD.Web
{
    public class IdempotenceFilter : IAsyncActionFilter, ITransientDependency
    {
        private ICacheManager CacheMgr { get; set; }
        private const string CacheName = "HCD.IdempotenceKey";
        public IdempotenceFilter(ICacheManager  cacheManager)
        {
            CacheMgr = cacheManager;
        }
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (context.HttpContext.Request.Method == HttpMethod.Post.Method)
            {
                var key = string.Concat(context.HttpContext.Connection.RemoteIpAddress, context.HttpContext.Request.Path, context.HttpContext.Request.ContentLength);
                if (await CacheMgr.GetCache<string, int>(CacheName).GetOrDefaultAsync(key) == 0)
                {
                    await CacheMgr.GetCache<string, int>(CacheName).SetAsync(key, 1, TimeSpan.FromSeconds(30));
                    context.HttpContext.Response.OnCompleted(async () =>
                    {
                        await CacheMgr.GetCache<string, int>(CacheName).RemoveAsync(key);
                    });
                    await next();
                }
            }
            else
                await next();
        }
    }
}
